package com.shaoshaohuo.app.ui.ec;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;

import com.shaoshaohuo.app.R;
import com.shaoshaohuo.app.constant.ExtraName;
import com.shaoshaohuo.app.entity.BaseEntity;
import com.shaoshaohuo.app.entity.MarketEntity;
import com.shaoshaohuo.app.net.HttpRequest.RequestListener;
import com.shaoshaohuo.app.net.RequestService;
import com.shaoshaohuo.app.ui.BaseActivity;
import com.shaoshaohuo.app.adapter.MarketSelectAdapter;
import com.shaoshaohuo.app.view.TopbarView;
import com.shaoshaohuo.app.entity.Market;
/**
 * 选择批发市场
 * @author cao
 *
 */
public class SelectMarketActivity extends BaseActivity {

	private TopbarView mTopbarView;

	private ListView mCityListview;

    protected Market market;

    private String cityid = "";
    private String name = "";
    
	@Override
	public void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_select_city);
		
		initData();
		initView();
		setUpView();
		requestData();
	}

	private void initData() {
	    Intent intent = getIntent();
	    cityid = intent.getStringExtra(ExtraName.citycode);
    }

    private void requestData() {
        startLoadingDialog();
	    RequestService.getInstance().ecMarketSearch(this, cityid, name, MarketEntity.class, new RequestListener() {
            
            @Override
            public void onSuccess(int requestCode, BaseEntity resultData) {
                dismissLoadingDialog();
                if(resultData.isOk()){
                    MarketEntity entity = (MarketEntity) resultData;
                    setAdapter(entity);
                }else{
                    showToast(resultData.getMsg());
                }
            }
            
            @Override
            public void onFailed(int requestCode, Exception error, String msg) {
                dismissLoadingDialog();
            }
        });
    }

    protected void setAdapter(MarketEntity entity) {
        MarketSelectAdapter<Market> mAdapter = new MarketSelectAdapter<>(this, entity.getData().getList(), false);
        mCityListview.setAdapter(mAdapter);
    }

    private void initView() {
		mTopbarView = (TopbarView) this.findViewById(R.id.topbar);
		mCityListview = (ListView) this.findViewById(R.id.listview_city_list);
	}

	private void setUpView() {
		mTopbarView.setCenterText("选择市场");
		mTopbarView.setLeftView(true, true);

		
		mCityListview.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
			    market = (Market) parent.getItemAtPosition(position);
			    Intent intent = new Intent();
			    intent.putExtra(ExtraName.market, market);
			    setResult(RESULT_OK, intent);
			    finish();
			}
		});
	}

}
